//
//  XMFCollectionView.swift
//  FlyingPigeon
//
//  Created by yang on 2019/5/26.
//  Copyright © 2019年 a. All rights reserved.
//

import Foundation
import UIKit




class YMFCollectionView: ViewController {
    
    var collectionView: UICollectionView!
    
    var dataArray = [YMFPriceModel]()
    
    var dataString = ""
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        let width: CGFloat = (view.bounds.size.width - 15) / 2
        layout.itemSize = CGSize(width: width, height: 200)
//        layout.sectionInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 0)
        
        
        collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.white
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor(red: 245 / 255.0, green: 245 / 255.0, blue: 245 / 255.0, alpha: 1.0)
        view.addSubview(collectionView)
        
        collectionView.register(UINib(nibName: "YMFCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "cell")
        let path = Bundle.main.path(forResource: "text", ofType: "txt")
        let jsonStr = try? NSString.init(contentsOfFile: path!, encoding: String.Encoding.utf8.rawValue)
        let jsonData = try! jsonStr!.data(using: String.Encoding.utf8.rawValue)
//        let data = try?Data(contentsOf: URL(fileURLWithPath: path!))
//        let data = FileManager().contents(atPath: Bundle.main.bundlePath + "SpecCarInfo.json")
//        let dataObj = try?JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
        
        let dataObj = try? JSONSerialization.jsonObject(with: jsonData!, options: JSONSerialization.ReadingOptions.allowFragments)
       
        
        if let array = dataObj as? [[String: String]] {
            array.forEach({ (item) in
                let model = YMFPriceModel(dict: item)
//                model.setValuesForKeys(item)
                dataArray.append(model)
            })
        }
    }
    
}

extension YMFCollectionView: UICollectionViewDelegate, UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
       
        (cell as? YMFCollectionViewCell)?.updateWithModel(model: dataArray[indexPath.row])
        return cell
        
    }
}
